package cn.schoolwow.starter.quickdao;

import cn.schoolwow.quickdao.dao.DAO;
import cn.schoolwow.quickdao.transaction.Transaction;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class QuickDAOTransactionManager extends AbstractPlatformTransactionManager {
    /**资源key*/
    public static final String QUICKDAO_RESOURCE_KEY = "QuickDAO_Transaction";

    /**dao对象*/
    private DAO dao;

    public QuickDAOTransactionManager(DAO dao) {
        this.dao = dao;
    }

    @Override
    protected Object doGetTransaction() throws TransactionException {
        QuickDAOTransactionObject quickDAOTransactionObject = new QuickDAOTransactionObject();
        quickDAOTransactionObject.setSavepointAllowed(isNestedTransactionAllowed());
        Transaction transaction = (Transaction) TransactionSynchronizationManager.getResource(QUICKDAO_RESOURCE_KEY);
        quickDAOTransactionObject.setTransaction(transaction);
        return quickDAOTransactionObject;
    }

    @Override
    protected void doBegin(Object o, TransactionDefinition transactionDefinition) throws TransactionException {
        QuickDAOTransactionObject quickDAOTransactionObject = (QuickDAOTransactionObject) o;
        if(null==quickDAOTransactionObject.getTransaction()){
            Transaction transaction = dao.startTransaction();
            quickDAOTransactionObject.setTransaction(transaction);
            TransactionSynchronizationManager.bindResource(QUICKDAO_RESOURCE_KEY,quickDAOTransactionObject);
        }
        Transaction transaction = quickDAOTransactionObject.getTransaction();
        if(transactionDefinition.getIsolationLevel()>0){
            transaction.setTransactionIsolation(transactionDefinition.getIsolationLevel());
        }
    }

    @Override
    protected void doCommit(DefaultTransactionStatus defaultTransactionStatus) throws TransactionException {
        QuickDAOTransactionObject quickDAOTransactionObject = (QuickDAOTransactionObject) defaultTransactionStatus.getTransaction();
        Transaction transaction = quickDAOTransactionObject.getTransaction();
        transaction.commit();
    }

    @Override
    protected void doRollback(DefaultTransactionStatus defaultTransactionStatus) throws TransactionException {
        QuickDAOTransactionObject quickDAOTransactionObject = (QuickDAOTransactionObject) defaultTransactionStatus.getTransaction();
        Transaction transaction = quickDAOTransactionObject.getTransaction();
        transaction.rollback();
    }
}
